//
//  ViewControllerExtension.swift
//  ReactNativeIOS
//
//  Created by 陆文宇 on 2017/11/27.
//  Copyright © 2017年 chenliang. All rights reserved.
//

import Foundation
import React
import Kingfisher

extension ViewController {
    func registerRNAction() {
        RNJsBridgeManager.getInstance().registerAction("getconfigvalue") { (params: [AnyHashable : Any]?, callback:RCTResponseSenderBlock?) in
            let keys = params?["keys"] as! String
            var values = [String: String]()
            keys.components(separatedBy: ",").forEach({ (key) in
                values[key] = YYAppConfig.getOne(key: key) ?? ""
            })
            callback?([values])
        }
        
        RNJsBridgeManager.getInstance().registerAction("setconfigvalue") { (params, callback) in
            let key = params?["key"] as! String
            let value = "\(params!["value"]!)"
            
            YYAppConfig.set(key: key, value: value)
        }
        
        RNJsBridgeManager.getInstance().registerAction("photoUtils") { (params, callback) in
            let type = params!["type"] as! String
            let size_w = params!["size_w"] as! CGFloat
            let size_h = params!["size_h"] as! CGFloat
            let token = params!["token"] as! String
            let filetag = params!["filetag"] as! String
            
            self.imageUpload = ImageUpload(type: type, size_w: size_w, size_h: size_h, token: token, filetag: filetag, doneClosure: { (filename) in
                callback?([["imgs": filename]])
            })
            self.imageUpload?.performOne()
        }
        
        RNJsBridgeManager.getInstance().registerAction("chooseMultiImgs") { (params, callback) in
            let num = params!["num"] as! Int
            let token = params!["token"] as! String
            let filetag = params!["filetag"] as! String
            
            self.imageUpload = ImageUpload(num: num, token: token, filetag: filetag, doneClosure: { (imgs) in
                callback?([["imgs": imgs]])
            })
            self.imageUpload?.performDuo()
        }
        
        RNJsBridgeManager.getInstance().registerAction("chooseCity") { (params, callback) in
            let city = ChooseCityViewController(nibName: "ChooseCityViewController", bundle: nil)
            city.chooseCityClosure = { (result) in
                var dic = [String: String]()
                if result.code.count == 6 {
                    dic["shen"] = YYCity.getOne(id: result.parentId)!.name
                    dic["shi"] = result.name
                    dic["xian"] = ""
                } else {
                    let shi = YYCity.getOne(id: result.parentId)!
                    dic["shen"] = YYCity.getOne(id: shi.parentId)!.name
                    dic["shi"] = shi.name
                    dic["xian"] = result.name
                }
                dic["city"] = result.name
                dic["code"] = result.code
                callback?([dic])
            }
            self.yy_present(vc: city)
        }
        
        RNJsBridgeManager.getInstance().registerAction("showloading") { (params, callback) in
            let info = params?["info"] as? String ?? ""
            self.yy_showStatusHUD(status: info)
        }
        
        RNJsBridgeManager.getInstance().registerAction("hideloading") { (params, callback) in
            self.yy_dismissHUD()
        }
        
        RNJsBridgeManager.getInstance().registerAction("navi") { (params, callback) in
            let router = params?["router"] as! String
            let params = params?["params"] as? [String: Any] ?? [:]
            YYRouter.pushToVC(of: router, params: params)
            
            yy_Log(router)
        }
        
        RNJsBridgeManager.getInstance().registerAction("getlocation") { (params, callback) in
            YYLocation.startLocation({ (_) in
                let address = YYLocation.getLocationCity()?.name ?? ""
                let (lat, lon) = YYLocation.getLocation()
                callback?([["address": address, "lat": lat, "lon": lon]])
            })
        }
        
        RNJsBridgeManager.getInstance().registerAction("showinfo") { (params, callback) in
            let info = params?["info"] as! String
            SVProgressHUD.showInfo(with: info)
        }
        
        RNJsBridgeManager.getInstance().registerAction("chooseMapLocation") { (params, callback) in
            let lat = "\(params!["lat"] ?? "")"
            let lon = "\(params!["lon"] ?? "")"
            
            let location = ChooseLocationViewController(nibName: nil, bundle: nil)
            location.lat = Double(lat)
            location.lng = Double(lon)
            location.chooseClosure = { (lat, lng) in
                callback?([["address": "", "lat": lat, "lon": lng]])
            }
            self.yy_push(vc: location)
        }
        
        RNJsBridgeManager.getInstance().registerAction("editRichContent") { (params, callback) in
            let title = params?["title"] as! String
            let filetag = params?["filetag"] as! String
            let value = params?["value"] as! String
            
            let rich = WordImageViewController(nibName: "WordImageViewController", bundle: nil)
            rich.title = title
            rich.filetag = filetag
            rich.content = value
            rich.doneClosure = { (content) in
                callback?([["value": content]])
            }
            self.yy_push(vc: rich)
        }
        
        RNJsBridgeManager.getInstance().registerAction("getGoodsCategory") { (params, callback) in
            let code = params?["code"] as? String
            let parentId = params?["parentId"] as? Int
            
            if let code = code,
                let cat = GoodsCategory.getOne(catCode: code) {
                    callback?([["catName": cat.catName, "catCode": cat.catCode, "catIndex": cat.catIndex, "enable": cat.enable, "isType": cat.isType, "parentId": cat.parentId, "sort": cat.sort, "catId": cat.catId]])
            } else if let parentId = parentId {
                let cats = GoodsCategory.getSubAll(catId: parentId).map({ (cat) -> [String: Any] in
                    return ["catName": cat.catName, "catCode": cat.catCode, "catIndex": cat.catIndex, "enable": cat.enable, "isType": cat.isType, "parentId": cat.parentId, "sort": cat.sort, "catId": cat.catId]
                })
                callback?([["list": cats]])
            }
            
        }
        
        RNJsBridgeManager.getInstance().registerAction("logout") { (params, callback) in
            YYAppConfig.deleteOne(key: "loginstate")
            YYAppConfig.deleteOne(key: "token")
            YYAppConfig.deleteOne(key: "shoplogo")
            YYAppConfig.deleteOne(key: "shopname")
            YYAppConfig.deleteOne(key: "shoptoken")
            YYAppConfig.deleteOne(key: "shopaddress")

            callback?([0])
        }
        
//        RNJsBridgeManager.getInstance().registerAction("getgoodsattrrelation") { (params, callback) in
//            if let catid = params?["catid"] as? Int {
//                let relations = GoodsAttributeRelation.getAll(catId: catid)
//                callback?([relations.map({ (relation) -> [String: Any] in
//                    let attr = GoodsAttribute.getOne(attrId: relation.attrId)!
//                    return ["attrId": attr.attrId, "attrName": attr.attrName, "sort": attr.sort, "isMain": attr.isMain, "isNormal": attr.isNormal, "isMust": attr.isMust, "isDefault": attr.isDefault, "sortNo": attr.sortNo, "inputType": attr.inputType, "dicId": attr.dicId, "valueType": attr.valueType, "categoryId": attr.categoryId]
//                })])
//            }
//        }
        
        RNJsBridgeManager.getInstance().registerAction("getgoodsattrrelation") { (params, callback) in
            if let catcode = params?["catcode"] as? String {
                yy_post(url: apiUrlPrex + "/s/attribute/getAttrByCatcode", parameters: ["catCode": catcode], success: { (data) in
                    callback?([(data as! [[String: Any]]).map({ (relation) -> [String: Any] in
                        let attr = GoodsAttribute.getOne(attrId: relation["attrId"] as! Int)!
                        return ["attrId": attr.attrId, "attrName": attr.attrName, "sort": attr.sort, "isMain": attr.isMain, "isNormal": attr.isNormal, "isMust": attr.isMust, "isDefault": attr.isDefault, "sortNo": attr.sortNo, "inputType": attr.inputType, "dicId": attr.dicId, "valueType": attr.valueType, "categoryId": attr.categoryId]
                    })])
                }, failure: { (errmsg) -> String? in
                    return errmsg
                })
            }
        }
        
        RNJsBridgeManager.getInstance().registerAction("getitemvalue") { (params, callback) in
            if let dicid = params?["dicid"] as? Int {
                let items = GoodsDicItem.getAll(dicId: dicid)
                callback?([items.map({ (item) -> [String: Any] in
                    return ["id": item.id, "dicId": item.dicId, "itemValue": item.itemValue, "sortNo": item.sortNo]
                })])
            }
        }
        
        RNJsBridgeManager.getInstance().registerAction("saveqr") { (params, callback) in
            self.yy_showStatusHUD(status: "正在下载...")
            
            if let qrString = params?["qr"] as? String,
                let logo = params?["logo"] as? String {
                KingfisherManager.shared.retrieveImage(with: URL(string: logo)!, options: nil, progressBlock: nil, completionHandler: { (image, error, _, _) in
                    if let image = image {
                        YYPhotoHandler.available(authorized: {
                            UIGraphicsBeginImageContextWithOptions(CGSize(width: 200, height: 200), false, 0);
                            qrString.qrCode().draw(in: CGRect(x: 0, y: 0, width: 200, height: 200))
                            #imageLiteral(resourceName: "empty").draw(in: CGRect(x: 85, y: 85, width: 30, height: 30))
                            image.yy_compress(for: .roundedRect, cornerRadius: 5).draw(in: CGRect(x: 86, y: 86, width: 28, height: 28))
                            if let image = UIGraphicsGetImageFromCurrentImageContext() {
                                YYPhotoHandler.addImagesIntoUserLibrary(images: [image]) { (_, success, error) in
                                    if success {
                                        self.yy_showSuccessHUD(status: "保存成功")
                                    } else {
                                        self.yy_showErrorHUD(status: "保存失败")
                                        yy_Log(error ?? "no errmsg")
                                    }
                                }
                            } else {
                                self.yy_showErrorHUD(status: "图片生成失败，请再试一遍")
                            }
                            UIGraphicsEndImageContext()
                        }, denied: {
                            self.yy_showErrorHUD(status: "未能获取相册权限")
                        })
                    }
                })
            }
        }
        
    }
    
}
